<template>
	<view class="wrap">
		<u-form class="form" :model="model" :rules="rules" ref="uForm" label-position="left" :errorType="['message']">
			<u-form-item label="主类型" prop="mainType" label-width="180">
				<u-radio-group v-model="model.mainType">
					<u-radio v-for="(item, index) in mainTypeList" :key="index" style="width: 250rpx;"
						:name="item.dictValue">{{item.dictLabel}}</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="金额" prop="quantity" label-width="180">
				<u-input placeholder="请输入金额" v-model="model.quantity" type="text" maxlength="10"></u-input>
			</u-form-item>
			<!-- <u-form-item label="单位" prop="unit" label-width="180">
				<u-radio-group v-model="model.unit">
					<u-radio v-for="(item, index) in unitList" :key="index"
						:name="item.value">{{item.name}}</u-radio>
				</u-radio-group>
			</u-form-item> -->
			<u-form-item v-if="type == 2 || type == 3" label="分店名称" prop="officeCode" label-width="180">
				<shop-selector v-model="model" :shop-list="officeSelectList" :field-config="{
					valueField: 'dictValue',
					labelField: 'dictLabel',
					displayField: 'dictLabel',
					placeholder: '搜索/选择分店名称',
					codeField: 'officeCode',
					nameField: 'officeName'
				}"></shop-selector>
			</u-form-item>
			<u-form-item v-if="type == 44" label="销售月份" prop="startSaleDate" label-width="180">
				<view class="picker-container">
                    <picker mode="date" fields="month" :value="model.startSaleDate" :end="maxDate" @change="bindDateChange">
                        <view class="picker-input">
                            {{model.startSaleDate || '选择销售月份'}}
                        </view>
                    </picker>
					<u-icon name="calendar" size="40" color="#909399" class="month-icon"></u-icon>
                    <u-icon v-if="model.startSaleDate" name="close-circle-fill" size="40" color="#909399" class="clear-icon" @click="clearSaleMonth"></u-icon>
                </view>
			</u-form-item>
			<u-form-item v-if="type != 44" :label="type == 9 ? '发生日期':'销售日期'" prop="startSaleDate" label-width="180">
				<uni-datetime-picker v-model="model.startSaleDate" type="date" value-format="yyyy-MM-dd" :end="maxDate" :placeholder="type == 9 ? '选择发生日期':'选择销售日期'"></uni-datetime-picker>
			</u-form-item>
			<u-form-item :label="remarksLabel" prop="remarks" label-width="180" label-position="top">
				<u-input type="textarea" placeholder="请输入备注" v-model="model.remarks" height="100" maxlength="100" />
			</u-form-item>
			<u-form-item v-if="type == 4||type == 5||type == 6||type == 9" :label="(type == 4 || type == 9) && !model.id ? '上传图片（必填）' : '上传图片（可选）'" prop="images" label-position="top">
				<js-uploadfile ref="uploadFile" v-model="image.dataMap" :biz-key="model.id" biz-type="saleManage_image"></js-uploadfile>
			</u-form-item>
		</u-form>
		<view class="form-footer">
			<u-button class="btn" type="primary" @click="submit">提交</u-button>
			<!-- <u-button class="btn" type="default" @click="cancel">关闭</u-button> -->
		</view>
	</view>
</template>
<script>
/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
import ShopSelector from '@/components/shop-selector/shop-selector.vue'

export default {
	components: {
		ShopSelector
	},
	computed: {
		remarksLabel() {
			// 如果主类型是13或27，备注标签显示"备注（必填）"
			if (this.model.mainType === '13' || this.model.mainType === '27') {
				return '备注（必填）';
			}
			return '备注';
		}
	},
	data() {
		return {
			type:1,
			status: 0,
			image:{
				dataMap: {
					saleManage_image: '',
					saleManage_image__del: ''
				}
			},
			model: {
				id: '',
				quantity: '',
				mainType: '01',
				unit: '01',
				officeCode: '',
				officeName: '',
				remarks:'',
				startSaleDate:'',
				subType:'',
				commissionId: '',
			},
			startSaleDate:'',
			officeSelectList: [],
			mainTypeList:[],
			maxDate: '', // 最大可选日期（今天）
			dictType:'sale_main_type',
			unitList:[
				{value:'01',name:'元'},
				// {value:'02',name:'张'}
			],
			rules: {
				quantity: [
					{
						required: true,
						message: '请输入金额',
						trigger: ['change','blur'],
					},
					{
						pattern: /^-?[0-9]+(\.[0-9]{1,2})?$/,
						message: '请输入正确的数字格式（最多两位小数）',
						trigger: ['change','blur'],
					}
				],
				officeCode: [
					{
						required: true,
						message: '请选择店铺',
						trigger: ['change','blur'],
					},
				],
				remarks: [
					{
						validator: (rule, value, callback) => {
							// 如果主类型是13或27，则备注必填
							if (this.model.mainType === '13' || this.model.mainType === '27') {
								if (!value || value.trim() === '') {
									return false;
								}
							}
							return true;
						},
						message: '请输入备注',
						trigger: ['change','blur'],
					}
				],
				images: [
					{
						validator: (rule, value, callback) => {
							// 只有在type==4或type==9且为添加模式时才验证必填
							if ((this.type == 4 || this.type == 9) && !this.model.id) {
								if (!this.image.dataMap.saleManage_image || this.image.dataMap.saleManage_image.trim() === '') {
									return false;
								}
							}
							return true;
						},
						message: '请上传图片',
						trigger: ['change','blur'],
					}
				]
			}
		};
	},
	onLoad(params){
		let that = this
		let title = '添加'
		let updata = ''
		// 获取当前时间并格式化为 yyyy-MM-dd HH:mm:ss
		const currentTime = new Date();
		const year = currentTime.getFullYear();
		const month = String(currentTime.getMonth() + 1).padStart(2, '0');
		const day = String(currentTime.getDate()).padStart(2, '0');
		const dateStr = `${year}-${month}-${day}`;
		const monthStr = `${year}-${month}`;
		// 设置最大可选日期为今天
		this.maxDate = dateStr;
		this.type = params.type
		if(params.item){
			updata = JSON.parse(params.item)
			this.model.id = updata.id
			this.model.quantity = updata.quantity
			this.model.startSaleDate = updata.startSaleDate
			this.model.remarks = updata.remarks
			this.model.unit = updata.unit
			this.model.subType = updata.subType
			this.model.commissionId = updata.commissionId || ''
			this.status = updata.status
			title='修改'
			if(this.type > 9){
				if(updata.subType == 'HM'){
					this.type = 1
				}else if(updata.subType == 'BFD'){
					this.type = 2
				}else if(updata.subType == 'GFD'){
					this.type = 3
				}else if(updata.subType == 'BDXL'){
					this.type = 4
				}else if(updata.subType == 'YJ'){
					if(updata.mainType == '10'){
						this.type = 5
					}else if(updata.mainType == '09'){
						this.type = 6
					}else if(updata.mainType == '11'){
						this.type = 7
					}else if(updata.mainType == '13'){
						this.type = 8
					}
				}else if(updata.subType == 'KZ'){
					this.type = 9
				}
			}
		}else{
			this.model.startSaleDate = dateStr
		}

		if(this.type == 1){
			this.dictType = 'hm_type'
			this.model.subType = 'HM'
		}else if(this.type == 2){
			this.dictType = 'bfd_type'
			this.model.subType = 'BFD'
		}else if(this.type == 3){
			this.dictType = 'gfd_type'
			this.model.subType = 'GFD'
		}else if(this.type == 4){
			this.dictType = 'bdxl_type'
			this.model.subType = 'BDXL'
		}else if(this.type == 5){
			this.dictType = 'yj_type'
			this.model.subType = 'YJ'
		}else if(this.type == 6){
			this.dictType = 'yj_type'
			this.model.subType = 'YJ'
		}else if(this.type == 7){
			this.dictType = 'yj_type'
			this.model.subType = 'YJ'
		}else if(this.type == 8){
			this.dictType = 'yj_type'
			this.model.subType = 'YJ'
		}else if(this.type == 9){
			this.dictType = 'kz_type'
			this.model.subType = 'KZ'
		}
		
		// 机构数据
		this.$u.api.mainType.treeData({dictType:'office_code'}).then(res => {
			this.officeSelectList = res;
			// 如果是编辑模式，设置选中的店铺
			if(params.item){
				this.model.officeCode = updata.officeCode
				this.model.officeName = updata.officeName
			}
		});
		// 主类型
		this.$u.api.mainType.treeData({dictType:this.dictType}).then(res => {
			// if(that.type == 1){
			// 	this.mainTypeList = res.filter(item => item.dictValue == '01' || item.dictValue == '12');
			// 	this.model.mainType = '01'
			// 	this.model.subType = 'HM'
			// }else if(that.type ==2){
			// 	this.mainTypeList = res.filter(item => item.dictValue == '02');
			// 	this.model.mainType = '02'
			// 	this.model.subType = 'BFD'
			// }else if(that.type ==3){
			// 	this.mainTypeList = res.filter(item => item.dictValue == '03');
			// 	this.model.mainType = '03'
			// 	this.model.subType = 'GFD'
			// }else if(that.type ==4){
			// 	this.mainTypeList = res.filter(item => item.dictValue == '04' || item.dictValue == '05'|| item.dictValue == '06' || item.dictValue == '07' || item.dictValue == '08' || item.dictValue == '28');
			// 	this.model.mainType = '04'
			// 	this.model.subType = 'BDXL'
			// 	// this.model.startSaleDate = monthStr
			// }else 
			if(that.type ==5){
				this.mainTypeList = res.filter(item => item.dictValue == '10');
				this.model.mainType = '10'
				this.model.subType = 'YJ'
			}else if(that.type ==6){
				this.mainTypeList = res.filter(item => item.dictValue == '09');
				this.model.mainType = '09'
				this.model.subType = 'YJ'
			}else if(that.type ==7){
				this.mainTypeList = res.filter(item => item.dictValue == '11');
				this.model.mainType = '11'
				this.model.subType = 'YJ'
			}else if(that.type ==8){
				this.mainTypeList = res.filter(item => item.dictValue == '13');
				this.model.mainType = '13'
				this.model.subType = 'YJ'
			}else{
				this.mainTypeList = res;
			}
			this.model.mainType = this.mainTypeList[0].dictValue;
			// else if(that.type ==9){
			// 	this.mainTypeList = res.filter(item => item.dictValue >= '14' && item.dictValue <= '27');
			// 	this.model.mainType = '14'
			// 	this.model.subType = 'KZ'
			// }
			if(params.item){
				this.model.mainType = updata.mainType
			}
		});
		uni.setNavigationBarTitle({
			title: title
		});
	},
	onReady() {
		// 设置表单规则
		this.$refs.uForm.setRules(this.rules);
		// 如果是编辑模式，则加载文件
		if (this.model.id) {
			this.$refs.uploadFile.loadData();
		}
	},
	methods: {
		submit() {
			this.$refs.uForm.validate(valid => {
				if (valid) {
					if(this.model.id && (this.status == 9 || this.status == 4)){
						this.$u.toast('该状态不能修改！');
						return;
					}
					if(this.model.mainType == '11' || this.model.mainType == '29' || this.model.mainType == '30' || this.model.mainType == '31'){
						this.$u.toast('该类型不能修改！');
						return;
					}
					// 检查是否为两个月前的数据（仅在编辑模式下检查）
					if(this.model.id && !this.isWithinTwoMonths(this.model.startSaleDate)){
						this.$u.toast('不能修改两个月前的数据！');
						return;
					}
					// 额外验证上传图片（仅在type==4或type==9且为添加模式时）
					if ((this.type == 4 || this.type == 9) && !this.model.id) {
						if (!this.image.dataMap.saleManage_image || this.image.dataMap.saleManage_image.trim() === '') {
							this.$u.toast('请上传图片');
							return;
						}
					}
					
					// 组织交款参数
					const paymentParams = {
						'id': this.model.id, 
						'quantity': this.model.quantity,
						'mainType': this.model.mainType,
						'unit': this.model.unit,
						'officeCode': this.model.officeCode,
						'officeName': this.model.officeName,
						'startSaleDate': this.model.startSaleDate,
						'subType': this.model.subType,
						'remarks': this.model.remarks,
						'dataMap[saleManage_image]': this.image.dataMap.saleManage_image || '',  // 交款记录图片数组
						'dataMap[saleManage_image__del]': this.image.dataMap.saleManage_image__del || '',   // 要删除的交款记录图片ID数组
					};
					
					// 如果 subType 是 BDXL，则添加 commissionId 参数
					if (this.model.subType === 'BDXL') {
						paymentParams.commissionId = this.model.commissionId;
					}
					this.$u.api.salesManagement.save(paymentParams).then(res => {
						uni.showModal({
							title: '提示',
							content: res.message,
							showCancel: false,
							success: function () {
								if (res.result == 'true') {
									uni.setStorageSync('refreshList', true);
									uni.navigateBack();
								}
							}
						});
					});
				} else {
					// this.$u.toast('您填写的信息有误，请根据提示修正。');
				}
			});
		},
		cancel() {
			uni.navigateBack();
		},
		bindDateChange: function(e) {
			this.model.startSaleDate = e.target.value
			console.log(this.model.startSaleDate)
		},
		clearSaleMonth() {
            this.model.startSaleDate = '';
        },
		// 检查日期是否在最近两个月内
		isWithinTwoMonths(recordDate) {
			if (!recordDate) return false;
			
			const today = new Date();
			const currentYear = today.getFullYear();
			const currentMonth = today.getMonth() + 1; // getMonth() 返回 0-11，需要 +1
			
			// 解析记录日期
			const recordDateObj = new Date(recordDate);
			const recordYear = recordDateObj.getFullYear();
			const recordMonth = recordDateObj.getMonth() + 1;
			
			// 计算最近两个月的范围
			let allowedMonths = [];
			for (let i = 0; i < 2; i++) {
				const month = currentMonth - i;
				const year = month < 0 ? currentYear - 1 : currentYear;
				allowedMonths.push({ year, month: month < 0 ? month + 12 : month });
			}
			
			const isWithinTwoMonths = allowedMonths.some(({ year, month }) => 
				recordYear === year && recordMonth === month
			);
			
			return isWithinTwoMonths;
		}
	}
};
</script>
<style lang="scss">
	/deep/.uni-date-single--x[data-v-6e13d7e2]{
		right: 0;
	}
	.picker-container {
		display: flex;
		align-items: center;
		position: relative;
	}

	.month-icon {
		position: absolute;
		left: 10px;
		top: 53%;
		transform: translateY(-50%);
	}

	.picker-input {
		width: 200px;
		padding: 0 0 0 30px;
		height: 40px;
		line-height: 40px;
		border: 1px solid #dcdcdc;
		border-radius: 4px;
		background-color: #ffffff;
		font-size: 14px;
		color: #333333;
		box-sizing: border-box;
	}

	.clear-icon {
		position: absolute;
		right: 10px;
		top: 53%;
		transform: translateY(-50%);
	}

	.shop-select {
		position: relative;
		width: 100%;
	}
	
	.shop-list {
		position: absolute;
		top: 100%;
		left: 0;
		right: 0;
		background: #fff;
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		max-height: 300rpx;
		overflow-y: auto;
		z-index: 100;
		box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
	}
	
	.shop-item {
		padding: 20rpx;
		border-bottom: 1px solid #eee;
		&:last-child {
			border-bottom: none;
		}
		&:active {
			background-color: #f5f7fa;
		}
	}
</style>
